﻿using System.Collections.Generic;
using System.Linq;
using Mnk.Merger.Code.Common;
using Mnk.Merger.Code.Settings;

namespace Mnk.Merger.Code.Repository
{
    class RepositoryProvider : IRepositoryProvider
    {
        private readonly ISerializer serializer;
        private readonly IProcessExecutor commands;
        private readonly MergeConfig config;

        public RepositoryProvider(ISerializer serializer, IProcessExecutor commands, MergeConfig config)
        {
            this.serializer = serializer;
            this.commands = commands;
            this.config = config;
        }

        public IList<SvnLogEntry> Collect(string url)
        {
            var command = "--stop-on-copy";
            if (!string.IsNullOrEmpty(config.MergeFrom))
            {
                command = "--use-merge-history -r" + config.MergeFrom + ":HEAD";
            }
            var p = commands.Execute(string.Format("svn log \"{0}\" {1} --xml", url, command));
            var entities = serializer.Deserialize<SvnLogEntities>(p.StandardOutput);
            if (!string.IsNullOrEmpty(config.MergeFrom))
            {
                var from = int.Parse(config.MergeFrom);
                return entities.LogEntries.Where(x=>int.Parse(x.Id) >= from ).ToArray();
            }
            return !entities.LogEntries.Any() ? 
                new SvnLogEntry[0] :
                entities.LogEntries.Skip(1).Reverse().ToArray();
        }
    }
}
